package tanhua.dubbo.server.api;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import com.tanhua.dubbo.server.mapper.HuanXinUserMapper;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.service.RequestService;
import com.tanhua.dubbo.server.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import tanhua.dubbo.server.enums.HuanXinMessageType;

import java.util.Arrays;
import java.util.Date;

/**
 * @program: my-tanhua
 * @description:
 * @author: xuejingjing
 * @create: 2021-10-07 14:17
 **/
@Service(version = "1.0.0")
@Slf4j
public class HuanXinApiImpl implements HuanXinApi{

    @Autowired
    private TokenService tokenService;

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RequestService requestService;

    @Autowired
    private HuanXinUserMapper huanXinUserMapper;

   @Override
    public Boolean register(Long userId) {
     //拼接url
        String targeturl = huanXinConfig.getUrl()+huanXinConfig.getOrgName()+"/" +
                huanXinConfig.getAppName() + "/users";

        HuanXinUser huanXinUser = new HuanXinUser();
        huanXinUser.setUsername("HX_"+ userId);
        huanXinUser.setPassword(IdUtil.simpleUUID());//随机生成的密码

        //发起请求
        HttpResponse response = requestService.execute(targeturl, JSONUtil.toJsonStr(Arrays.asList(huanXinUser)), Method.POST);
        if (response.isOk()) {
            //说明注册成功了
            //将环信的账号信息保存到数据库中
            huanXinUser.setUserId(userId);
            huanXinUser.setCreated(new Date());
            huanXinUser.setUpdated(huanXinUser.getCreated());
            //根据mapper插入数据
          huanXinUserMapper.insert(huanXinUser);
          return true;
        }

        return false;
    }

    @Override
    public HuanXinUser queryHuanXinUser(Long userId) {
       //根据mapper查询
        /**
         * huanXinUserMapper.selectById();
         * huanXinUserMapper.selectOne();的区别
         * 主要是id,
         */
        QueryWrapper<HuanXinUser> query = new QueryWrapper<>();
        query.eq("user_id",userId);
        huanXinUserMapper.selectOne(query);

        return null;
    }

    @Override
    public String getToken() {
        return tokenService.getToken();
    }


    @Override
    public HuanXinUser queryUserByUserName(String userName) {
       QueryWrapper<HuanXinUser> query = new QueryWrapper<>();
       query.eq("userName",userName);
        HuanXinUser huanXinUser = huanXinUserMapper.selectOne(query);
        if(ObjectUtil.isNotEmpty(huanXinUser)){
             return huanXinUser;
        }
        return null;
    }

    @Override
    public HuanXinUser queryUserInfoByUserId(Long userId) {
        QueryWrapper<HuanXinUser> query = new QueryWrapper<>();
        query.eq("user_id",userId);
        HuanXinUser huanXinUser = huanXinUserMapper.selectOne(query);
        if(ObjectUtil.isNotEmpty(huanXinUser)){
            return huanXinUser;
        }
        return null;
    }


    //这是环信的方法。用来绑定朋友关系。也就是注绑定到环信。
    @Override
    public Boolean addUserFriend(Long userId, Long friendId) {
        String targetUrl = this.huanXinConfig.getUrl()
                + this.huanXinConfig.getOrgName() + "/"
                + this.huanXinConfig.getAppName() + "/users/HX_" +
                userId + "/contacts/users/HX_" + friendId;
        try {
            // 404 -> 对方未在环信注册
            return this.requestService.execute(targetUrl, null, Method.POST).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 添加失败
        return false;
    }

    @Override
    public Boolean removeUserFriend(Long userId, Long friendId) {
        String targetUrl = this.huanXinConfig.getUrl()
                + this.huanXinConfig.getOrgName() + "/"
                + this.huanXinConfig.getAppName() + "/users/HX_" +
                userId + "/contacts/users/HX_" + friendId;
        try {
            // 404 -> 对方未在环信注册
            return this.requestService.execute(targetUrl, null, Method.DELETE).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 添加失败
        return false;
    }

    /**
     *  * 以管理员身份发送消息
     *      * 文档地址：http://docs-im.easemob.com/im/server/basics/messages#%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF
     * @param targetUserName
     * @param huanXinMessageType
     * @param msg
     * @return
     */
    @Override
    public Boolean sendMsgFromAdmin(String targetUserName, HuanXinMessageType huanXinMessageType, String msg) {
        try {
            String  targetUrl = huanXinConfig.getUrl()
                    + huanXinConfig.getOrgName()+"/"
                    +huanXinConfig.getAppName()+"/message";

            String body = JSONUtil.createObj().set("target_type","users")
                          .set("target",JSONUtil.createArray().add(targetUserName))
                          .set("msg",JSONUtil.createObj()
                                               .set("type",huanXinMessageType.getType())
                                               .set("msg",msg)).toString();
            //环信接口请求服务
            return  requestService.execute(targetUrl,body,Method.POST).isOk();
        } catch (JSONException e) {
            log.error("发送消息失败~"+targetUserName+huanXinMessageType+msg);
            e.printStackTrace();
        }
    }

}